<script lang="ts" setup>
  import { audioPlay } from '@/components/index'
  import { getLyrics, getMusicUrl, getNewMusic } from '@/http/api/search'
  import { nextTick, onMounted, ref } from 'vue'
  import { useRoute } from 'vue-router'
  import ProgressBar from '../components/progress.vue'

  let name = useRoute().query.name as string
  let styleSheet: HTMLStyleElement | null = null
  const id: any = useRoute().query.id
  const lyrics = ref<any>('')
  const musicUrl = ref('')
  const audioInstance = ref<ReturnType<typeof audioPlay>>()
  const play = ref(false)
  const musicUrlList = ref<{
    id: number,
    name: string,
  }[]>([{
    id: 0,
    name: '',
  }])
  const limit = ref(10)
  const activeMusic = ref(0)
  const currentTime = ref()
  const totalTime = ref()

  onMounted(async () => {
    // updateBgURL()

    // 获取推荐歌曲列表
    musicUrlList.value = []
    musicUrlList.value = await getMusicList()

    musicUrl.value = await getLyric({
      musicId: musicUrlList.value[activeMusic.value].id,
      musicName: musicUrlList.value[activeMusic.value].name,
    })
    audioInstance.value = audioPlay(musicUrl.value)

    await nextTick(() => playMusic())

    // 设置总时长 当前时间
    currentTime.value = audioInstance.value.getCurrentTime()
    totalTime.value = audioInstance.value.getDuration()
    setInterval(() => {
      if (play.value) {
        currentTime.value = audioInstance.value.getCurrentTime()
      }
    }, 100)

    // 播放完成
    audioInstance.value.handleEnded(async () => {
      play.value = false
      if (activeMusic.value + 1 >= musicUrlList.value.length) {
        limit.value += 10
        // updateBgURL()
        musicUrlList.value = await getMusicList()
      }
      if (audioInstance.value) {
        activeMusic.value += 1
        musicUrl.value = await getLyric({
          musicId: musicUrlList.value[activeMusic.value].id,
          musicName: musicUrlList.value[activeMusic.value].name,
        })
        await audioInstance.value.handoffMusic(musicUrl.value)
      }
    })
  })

  // 更改背景图
  const updateBgURL = () => {
    if (!styleSheet) {
      styleSheet = document.createElement('style')
      document.head.appendChild(styleSheet)
    }
    styleSheet.innerHTML = `.play::before {
                            content: "";
                            position: absolute;
                            top: 0;
                            left: 0;
                            width: 100%;
                            height: 100%;
                            background: url('http://47.120.55.228/image?t=${new Date().getTime()}') 100% 100%;
                            background-size: cover;
                          }`
  }

  // 获取推荐歌曲列表并去重
  const getMusicList = async () => {
    const data = (await getNewMusic(limit.value)).result.map(v => ({
      name: v.name,
      id: v.id,
    }))
    const result = [...musicUrlList.value, ...data]
    const uniqueResult = result.filter((value, index, self) =>
      index === self.findIndex(t => (
        t.id === value.id
      ))
    )
    return [{
      name,
      id: +id,
    }, ...uniqueResult]
  }

  // 获取&解析歌词&返回歌曲URL
  const getLyric = async ({
    musicId,
    musicName,
  }: { musicId: number, musicName: string }) => {
    const data = (await getLyrics(musicId)).lrc.lyric
    const lyric = data.match(/(?<=\d{2}:\d{2}.\d{2,3}]\s?).*/g)
    name = musicName
    lyrics.value = lyric?.map(v => `<div class="lyric">${v.trim()}</div>`).join('\n')
    return getMusicUrl(musicId)
  }

  // 播放
  const playMusic = async () => {
    if (!play.value && audioInstance.value) {
      await audioInstance.value.playAudio().catch((err: string) => {
        play.value = false
        throw new Error(err)
      })
      play.value = true
    }
  }

  // 暂停
  const paused = () => {
    if (play.value && audioInstance.value) {
      audioInstance.value.pauseAudio()
      play.value = false
    }
  }

  // 切换歌曲
  const handoffMusic = async (type: 'up' | 'down') => {
    if (audioInstance.value) {
      // updateBgURL()
      play.value = false
      activeMusic.value = type === 'up' ? (activeMusic.value !== 0 ? activeMusic.value - 1 : activeMusic.value) : activeMusic.value + 1
      if (activeMusic.value + 1 >= musicUrlList.value.length) {
        limit.value += 10
        musicUrlList.value = await getMusicList()
      }
      musicUrl.value = await getLyric({
        musicId: musicUrlList.value[activeMusic.value].id,
        musicName: musicUrlList.value[activeMusic.value].name,
      })
      await audioInstance.value.handoffMusic(musicUrl.value)
      play.value = true
    }
  }

  // 调整进度
  const updateTime = (newTime: number) => {
    if (audioInstance.value) {
      audioInstance.value.setCurrentTime(newTime)
    }
  }
</script>

<template>
  <div class="play">
    <div class="content">
      <div class="title">{{ name }}</div>
      <div class="lyrics" v-html="lyrics" />
      <progress-bar :current-time="currentTime" :total-time="totalTime" @update-time="updateTime" />
      <div class="playMusic">
        <div class="up" @click="handoffMusic('up')">
          <svg
            class="icon"
            height="32"
            p-id="7274"
            t="1731634933572"
            version="1.1"
            viewBox="0 0 1171 1024"
            width="32"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path
              d="M49.486529 0.618582a49.486529 49.486529 0 0 0-49.486529 49.486529v923.789778a49.486529 49.486529 0 0 0 98.973058 0V50.105111a49.486529 49.486529 0 0 0-49.486529-49.486529zM872.818654 27.58874l-533.217349 313.744593a197.946116 197.946116 0 0 0 0 341.333334l533.217349 313.744593a197.946116 197.946116 0 0 0 298.40377-170.728525V197.946116A197.946116 197.946116 0 0 0 872.818654 27.58874z m199.430712 798.093995v8.783859a98.973058 98.973058 0 0 1-148.459587 76.580404L389.706415 597.302404l-8.165277-5.319802a98.973058 98.973058 0 0 1 8.165277-165.285006L923.047481 112.953002l7.670412-4.082638A98.973058 98.973058 0 0 1 1072.249366 197.946116z"
              fill="#515151"
              p-id="7275"
            />
          </svg>
        </div>
        <div class="center">
          <svg
            v-if="!play"
            class="icon"
            height="40"
            p-id="9535"
            t="1731640404699"
            version="1.1"
            viewBox="0 0 1024 1024"
            width="40"
            xmlns="http://www.w3.org/2000/svg"
            @click="playMusic"
          >
            <path
              d="M725.632 827.904c-63.104 42.88-136.832 65.408-213.504 65.408-210.304 0-381.312-171.008-381.312-381.184 0-75.52 22.016-148.608 63.744-211.072 8.576-12.672 4.992-29.952-7.68-38.528-12.672-8.576-29.952-4.992-38.528 7.68-47.872 71.68-73.088 155.392-73.088 241.92 0 240.768 195.968 436.608 436.864 436.608 87.68 0 172.416-25.856 244.736-74.88 12.672-8.576 16-25.856 7.424-38.656-8.704-12.544-25.984-15.872-38.656-7.296zM512 75.136c-93.312 0-182.272 28.928-257.408 83.84-12.416 9.088-15.104 26.496-6.016 38.784 9.088 12.416 26.496 15.104 38.784 6.016 65.536-47.744 143.232-73.088 224.64-73.088 210.176 0 381.184 171.136 381.184 381.312 0 81.408-25.216 159.104-73.088 224.512-9.088 12.416-6.272 29.824 6.016 38.784 4.864 3.712 10.624 5.376 16.384 5.376 8.576 0 17.024-3.968 22.4-11.52 54.912-75.136 83.84-164.096 83.84-257.28C948.864 271.104 753.024 75.136 512 75.136z m-84.864 611.968c4.864 0 9.6-1.152 13.952-3.84l251.904-145.408c8.576-4.864 13.824-14.08 13.824-24.064 0-9.984-5.248-19.072-13.824-24.064L441.216 344.32c-8.704-4.864-19.2-4.864-27.904 0-8.576 4.864-13.824 14.08-13.824 24.064V659.2c0 9.984 5.248 19.072 13.824 24.064 4.224 2.56 9.088 3.84 13.824 3.84z m27.904-270.592l168.576 97.28-168.576 97.28v-194.56z"
              fill="#515151"
              p-id="9536"
            />
          </svg>
          <svg
            v-else
            class="icon"
            height="35"
            p-id="10669"
            t="1731640600962"
            version="1.1"
            viewBox="0 0 1048 1024"
            width="35"
            xmlns="http://www.w3.org/2000/svg"
            @click="paused"
          >
            <path
              d="M524.272128 0.018022C241.513165 0.018022 12.288102 229.245952 12.288102 512.005018c0 112.734003 36.43904 216.957952 98.17897 301.537997l38.667981-40.258048C97.458176 699.230003 67.143168 609.158963 67.143168 512.005018 67.143168 259.540992 271.807078 54.872986 524.272128 54.872986c252.45696 0 457.120973 204.668006 457.120973 457.132032 0 252.460954-204.664013 457.118003-457.120973 457.118003-96.240026 0-185.530982-29.744026-259.189043-80.53504l-34.539008 42.797978c83.150029 58.344038 184.437965 92.596019 293.728973 92.596019 282.758963 0 511.984026-229.220966 511.984026-511.976038C1036.256154 229.245952 807.031091 0.018022 524.272128 0.018022zM615.693107 256.011981l0 511.987 54.855 0L670.548107 256.012 615.693128 256.012zM377.996083 256.011981l0 511.987 54.855 0L432.851083 256.012 377.996128 256.012z"
              fill="#515151"
              p-id="10670"
            />
          </svg>
        </div>
        <div class="down" @click="handoffMusic('down')">
          <svg
            class="icon"
            height="32"
            p-id="8422"
            t="1731635579341"
            version="1.1"
            viewBox="0 0 1024 1024"
            width="32"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path
              d="M768 401.066667L234.666667 68.266667C149.333333 21.333333 42.666667 81.066667 42.666667 179.2v665.6c0 98.133333 106.666667 162.133333 192 110.933333L768 622.933333c85.333333-51.2 85.333333-170.666667 0-221.866666z m-42.666667 149.333333L192 883.2c-29.866667 12.8-64-4.266667-64-38.4V179.2c0-34.133333 34.133333-51.2 64-38.4L725.333333 473.6c29.866667 17.066667 29.866667 59.733333 0 76.8z"
              fill="#515151"
              p-id="8423"
            />
            <path
              d="M853.333333 128c0-25.6 17.066667-42.666667 42.666667-42.666667s42.666667 17.066667 42.666667 42.666667v768c0 25.6-17.066667 42.666667-42.666667 42.666667s-42.666667-17.066667-42.666667-42.666667V128z"
              fill="#515151"
              p-id="8424"
            />
          </svg>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.play {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  position: relative;
  padding-top: 16px;

  .content {
    width: 100%;
    height: 100%;
    position: relative;
    //color: white;

    .title {
      margin: auto;
      max-width: 300px;
      white-space: nowrap; /* 禁止文本换行 */
      overflow: hidden; /* 隐藏超出范围的内容 */
      text-overflow: ellipsis; /* 使用省略号 */

      text-align: center;
      font-size: 18px;
      font-weight: bolder;
    }

    .lyrics {
      width: 100%;
      height: 85%;
      margin-top: 20px;
      //border: 1px solid red;
      overflow: hidden;
      overflow-y: auto;
    }

    .playMusic {
      display: flex;
      justify-content: space-around;
      align-items: center;
      width: 100%;
      height: 50px;
      position: absolute;
      bottom: 10px;

      div {
        height: 100%;
        //border: 1px solid red;
        display: flex;
        align-items: center;
      }
    }
  }
}
</style>
<style lang="scss">
.lyric {
  text-align: center;
  margin-bottom: 5px;
  font-size: 15px;
  font-weight: bolder;
}
</style>
